/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package session

import (
	"net/rpc"
	"net/http"
)

type Client struct {
	client *rpc.Client
}

func (c *Client) GetHttpSession(writer http.ResponseWriter, r *http.Request) (s *Session, err error) {
	id := HttpCookeSessionID(writer, r)
	return c.GetSession(id)
}

func (c *Client) GetSession(id string) (s *Session, err error) {
	var replay = make(map[string]string)
	err = c.client.Call("RpcContainer.GetValues", id, &replay)
	if err != nil {
		return nil, err
	} else {
		s = &Session{
			id: id,
			values: replay,
			changed:false,
		}
	}
	return
}

func (c *Client) SaveSession(s *Session) error {
	if s.changed {
		args := &SaveArgs {
			ID: s.id,
			Values: s.values,
		}
		err := c.client.Call("RpcContainer.SaveValues", args, &struct{}{})
		if err != nil {
			return err
		} else {
			s.changed = false
		}
	}
	return nil
}

// 新建 rpc 客户端
func NewClient(address string) (c *Client, e error) {
	client, err := rpc.DialHTTP("tcp", address)
	if err != nil {
		return nil, err
	} else {
		return &Client{client:client}, nil
	}
}